package com.psds.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

/**
 * author: cjianquan
 * date: 2016/8/25
 */
public class QuartzFactory {

    private final static Logger log = LoggerFactory.getLogger(QuartzFactory.class);

    private  static Scheduler scheduler;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

    private static boolean shutdownFlag = false;

    /**
     * 实例化scheduler
     * @throws org.quartz.SchedulerException
     */
    private static synchronized void  init() throws SchedulerException{
        if(scheduler==null){
            //Grab the Scheduler instance from the Factory
            scheduler = StdSchedulerFactory.getDefaultScheduler();
        }
    }

    /**
     * 启动定时任务
     * @param jobClazz
     * @param jobCron
     */
    public static void start(Class <? extends Job> jobClazz,String jobCron){
        start("job-"+sdf.format(new Date()),jobClazz,jobCron);
    }

    public static void start(String jobName,Class <? extends Job> jobClazz,String jobCron){
        start(jobName,"tri-"+sdf.format(new Date()),"group-"+sdf.format(new Date()),jobClazz,jobCron);
    }

    public static void start(String jobName,String triggerName,Class <? extends Job> jobClazz,String jobCron){
        start(jobName,triggerName,"group-"+sdf.format(new Date()),jobClazz,jobCron);
    }

    public static void start(String jobName,String triggerName,String groupName,Class <? extends Job> jobClazz,String jobCron){
        try {
            init();
            scheduler.start();
            JobDetail job = newJob(jobClazz)
                    .withIdentity(jobName, groupName)
                    .build();

            // Trigger the job to run now, and then repeat every 1 seconds
            Trigger trigger = newTrigger()
                    .withIdentity(triggerName, groupName)
                    .startNow()
                    .withSchedule(cronSchedule(jobCron))
                    .build();

            // Tell quartz to schedule the job using our trigger
            scheduler.scheduleJob(job, trigger);

            while (!shutdownFlag){}

        } catch (SchedulerException e) {
            log.error(e.getMessage(), e);
        }
    }

    public static void shutdown(){
        try {
            if(scheduler!=null){
                if(!scheduler.isShutdown()){
                    scheduler.shutdown();
                }
            }
        } catch (SchedulerException e) {
            log.error(e.getMessage(),e);
        }finally {
            shutdownFlag = true;
        }
    }
}
